<template>
  <!-- 上传 -->
  <div>
    <div class="uploadDiv" v-for="(item, index) in accList" :key="index">
      <div class="title_div">
        <span
        ><b v-if="item.info.itemValue == 1" style="color: red">*</b>上传{{
            item.info.itemText
          }}</span
        >

        <div>
          <el-button
            size="small"
            class="downloadImagee"
            @click="download(item)"
            v-if="item.data.length > 0 && item.data[0].type != 2"
          >下载
          </el-button
          >
          <input style="display: none"  @change="uploadData" ref="files" type="file" accept multiple />
          <el-button
            size="small"
            class="addpic"
            @click="getOrderNumber(item.info.itemValue, index)"
          >上传
          </el-button
          >

        </div>

      </div>
      <div
        class="upload_list listCart"
        v-loading="loading0"
        element-loading-text="拼命上传中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :style="{ 'min-height': height0 + 'px' }"
      >
        <ul class="clearfix" :id="'jq' + index">
          <li v-for="(item1, index1) in item.data" :key="item1.id">
            <div v-if="item1.accessoryType == 8">
              <div class="img">
                <el-image
                  style="width: 160px; height: 90px"
                  :src="item1.accessoryShrinkName"
                  fit="cover"
                  :lazy="true"
                >
                </el-image>
              </div>
              <el-tooltip
                class="item"
                effect="dark"
                :content="item1.accessoryName"
                placement="top-start"
              >
                <p class="name">{{ item1.accessoryName }}</p>
              </el-tooltip>
              <p class="ztc">{{ item1.accessorySize }} MB</p>
              <p class="ztc">{{ item1.upEmployeeName }}上传</p>
              <div class="btn">
                <el-button type="text" @click="reviewVideo(item1)"
                >查看
                </el-button
                >
                <span v-if="showdeleteBtn">
                  <el-popconfirm
                    title="确定删除此数据吗？"
                    @onConfirm="deleteData(item1.id)"
                    v-if="
                      orderStatus == -2 || orderStatus == 0 || orderStatus == 1
                    "
                  >
                    <el-button
                      slot="reference"
                      type="text"
                      size="small"
                      class="deteBtnText"
                      v-if="
                        orderStatus == -2 ||
                        orderStatus == 0 ||
                        orderStatus == 1
                      "
                    >删除</el-button
                    >
                  </el-popconfirm>
                </span>
              </div>
            </div>
            <div v-else>
              <img
                style="width: 160px; height: 90px; border-radius: 10px"
                :src="item1.showUrlMin"
                :ref="index + index1 + `img`"
                :realurl="item1.showUrl"
                :showName="item1.accessoryName"
              />
              <button
                :id="index1"
                class="viewButton"
                @click="viewImg(index, index1 + 'img', item1)"
              >
                查看
              </button>
              <span v-if="showdeleteBtn" class="deleteStyle">
                <el-popconfirm
                  title="确定删除此数据吗？"
                  @onConfirm="deleteData(item1.id)"
                  v-if="
                    orderStatus == -2 || orderStatus == 0 || orderStatus == 1
                  "
                >
                  <el-button
                    slot="reference"
                    type="text"
                    size="small"
                    class="deteBtnText"
                    v-if="
                      orderStatus == -2 || orderStatus == 0 || orderStatus == 1
                    "
                  >删除</el-button
                  >
                </el-popconfirm>
              </span>
              <div class="titleStyle">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="item1.accessoryName"
                  placement="top-start"
                >
                  <p class="name">{{ item1.accessoryName }}</p>
                </el-tooltip>
                <p class="ztc">{{ item1.accessorySize }} MB</p>
                <p class="ztc">{{ item1.upEmployeeName }}上传</p>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div>
      <el-dialog
        title="查看视频"
        :visible.sync="dialogVisiblee"
        width="30%"
        class="diaBox"
        :before-close="handleDialogClosee"
      >
        <video
          class="videoStyle"
          :src="src"
          style="width: 100%;"
          controls="controls"
          autoplay="autoplay"
        ></video>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisiblee = false">关 闭</el-button>
        </span>
      </el-dialog>
    </div>
    <div id="container">
      <div id="selectfiles"></div>
    </div>
  </div>

</template>
<script>
import {
  getOrderNumber,
  delOssPic,
  productDetails,
  getProductUrl,
  getOssOrder,
  addOrderImg,
  // getDDImgType,
  getImgCode
} from "../../../src/assets/js/api";
import { checkPermiss, tUploader } from "../../assets/js/utlis";
import JSZip from "jszip";
import FileSaver from "file-saver";
// import axios from "axios";
// import fileDownload from "js-file-download";
export default {
  name: "Upload",
  props: {
    isNew: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      accList: [],
      widths: "px",
      boxs: "inline - block",
      width: "",
      height: "",
      srcs: "", //遮罩层大图地址！
      imgIndex: "",
      showViewer: false, //遮罩层开关!
      indexList: [], //遮罩层轮播图数组!
      buildName: null, //下载图片打包的名字!
      address: [], //各图片类型的下载地址!
      imageName: [], //各类型图片的名字!
      imageSwitch: false, //图片放大弹窗开关!
      dialogVisiblee: false, //视频弹窗!
      typeArray: [],
      imgDownloadName: "",
      dialogImageUrl: "",
      dialogVisibleImg: false,
      stsdata: null,
      orderStatus: "",
      orderNumber: null,
      prductId: null,
      fileType: "",
      fileList: [],
      fileListBack: [],
      fileListHu: [],
      fileListMarry: [],
      fileListWork: [],
      fileListHouse: [],
      fileListZhen: [],
      fileListOther: [],
      loading0: false,
      loading1: false,
      loading2: false,
      loading3: false,
      loading4: false,
      loading5: false,
      loading6: false,
      loading7: false,

      height1: "0",
      height0: "0",
      height2: "0",
      height3: "0",
      height4: "0",
      height5: "0",
      height6: "0",
      height7: "0",
      src: "",
      imgUrl: "",
      golbalPermissions: [],
      type: 1,
      faceBack: "face",
      num0: 0,
      num1: 1,
      num2: 0,
      num3: 0,
      num4: 0,
      num5: 0,
      num6: 0,
      num7: 0,
      // 上传实例
      uploader: null,
      uploadFile: [],
      ossInfo: {}
    };
  },
  created() {
    this.golbalPermissions = localStorage.getItem("permissions").split(",");
    //产品ID
    this.productId = parseInt(sessionStorage.getItem("prductId"));
    //获取订单号
    if (this.isNew == false) {
      this.getOrderNum();
      this.findProductUrl(this.orderNumber);
    }
    this.getOrderFileByNumber(this.orderNumber || "");
    // this.getOssOrder();

  },
  mounted() {
    this.uploader = tUploader(this.uploaderCallback());

  },
  computed: {
    srcList: function() {
      return this.src.split(" ");
    },
    //上传附件按钮
    showAccessorySave: function() {
      return checkPermiss("business:accessory:save", this.golbalPermissions);
    },
    //删除附件按钮
    showdeleteBtn: function() {
      return checkPermiss("business:accessory:delete", this.golbalPermissions);
    }
  },
  fileForm: {},
  methods: {
    //上传视频回调
   async uploaderCallback() {
      let props = {};
      props.success = (up, file, info) => {
        if (info.status == 200) {
          this.addImg(this.fileForm, this.type);
        } else {
          this[`loading${this.type}`] = false;
          this[`height${this.type}`] = 0;
        }
      };
      return props;
    },
    // 图片查看功能!
    viewImg(index, refName) {
      this.$refs[`${index + refName}`][0].click();
    },
    // 查看视频详情弹窗右上角监听事件!
    handleDialogClosee() {
      this.dialogVisiblee = false; //关闭弹窗!
    },
    // 获取授权下载地址!
    async getOssDownLoadUrl(oldurl, fileName) {
      let url = "";
      if (!this.stsdata) {
        await getImgCode().then((res) => {
          if (res) {
            this.stsdata = res.data;
          }
        });
      }
      // 创建oss对象！
      const OSS = require("ali-oss");
      const client = new OSS({
        // region填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou!
        region: "oss-cn-chengdu",
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: this.stsdata.accessKeyId,
        accessKeySecret: this.stsdata.accessKeySecret,
        // 从STS服务获取的安全令牌（SecurityToken）。
        stsToken: this.stsdata.securityToken,
        // 填写Bucket名称。
        bucket: "drxf-oss"
      });
      const response = {
        "content-disposition": `attachment; filename=${encodeURIComponent(
          fileName
        )}`
      };
      // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
      url = client.signatureUrl(oldurl.substring(oldurl.indexOf("static")), {
        response
      });

      return url;
    },
    //定义一个base64打包的方法!
    async packaging(name, baseList, address, num, zipName, loading) {
      //转换为授权下载地址
      address = await this.getOssDownLoadUrl(address, name);
      if (!address) {
        this.$message.error(`请稍候再试`);
        return;
      }
      // packaging方法后面第一个参数name是数组对象的key,baseList是去掉base64编码前的 是存放图片地址的数组,num是存放图片地址数组的长度,zipName是压缩包的名字,loading是模态框!
      let imgName = name; //数组对象的key赋值给imgName!
      let image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.crossOrigin = "Anonymous";
      image.onload = function() {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL("image/jpeg", 0.6); // 得到图片的base64编码数据,默认是jpeg格式!好处,文件小!
        let temp = { [imgName]: url.substring(22) }; //temp等于{对象key:去掉图片的base64编码前22位字符的数据!}key是图片的名字!他的值是图片的地址!
        baseList.push(temp); //把得到的key对象赋值到baseList数组里面!
        var blogTitle = zipName; //声明blogTitle,并且把压缩包的名字赋值给blogTitle!
        var zip = new JSZip();
        var imgs = zip.folder(zipName);
        //如果存放编码后数组的长度等于存放图片地址的长度!
        if (baseList.length === num) {
          //这个for循环拿到数组对象的索引!
          for (var item in baseList) {
            //这个for循环拿到对象的key,也就是图片的名字!
            for (var it in baseList[item]) {
              //imgs.file后面的参数分别是(图片名字,编码后的图片地址,开启base64编码下载!)
              imgs.file(it, baseList[item][it], { base64: true });
            }
          }
          zip.generateAsync({ type: "blob" }).then(function(content) {
            FileSaver.saveAs(content, blogTitle + ".zip");
            loading.close(); //关闭模态框!
          });
        }
      };
      image.src = address;
    },
    //下载图片功能!
    async download(data) {
      //开启模态框!
      let loading = this.$loading({
        lock: false,
        text: "正在打包下载,请稍等...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      var dataArray = data.data; //各类型图片数据!

      //base64编码去掉前22位字符后的baselist数组!
      var baseList = [];
      //初始化类型名称
      this.buildName = data.info.itemText;
      // 要下载图片的url
      var arr = this.address;
      // 下载后图片的文件名，个数应与arr对应
      var imgNameList = this.imageName;
      for (let i = 0; i < dataArray.length; i++) {
        this.address.push(dataArray[i].showUrl);
        this.imageName.push(dataArray[i].accessoryName);
      }

      for (var i = 0; i < arr.length; i++) {
        // 这里循环得到图片下载地址,图片名字!
        await this.packaging(
          imgNameList[i],
          baseList,
          arr[i],
          arr.length,
          this.buildName,
          loading
        );
      }
      this.stsdata = null;
      this.address = [];
      this.imageName = [];
      this.buildName = [];
    },
    //根据订单查询订单状态
    findProductUrl(orderNumber) {
      getProductUrl({
        orderNumber: orderNumber
      }).then((res) => {
        this.orderStatus = res.data.orderStatus;
      });
    },
    //判断获取orderNumber
    getOrderNum() {
      let orderNumber = this.$route.query.orderNumber;
      if (orderNumber) {
        this.orderNumber = orderNumber;
      } else {
        this.orderNumber = sessionStorage.getItem("orderNumber");
      }
    },
    //获取图片尺寸!
    async getData() {
      let that = this;
      let img_url = this.srcs;
      let img = new Image();
      img.src = img_url;
      img.onload = function() {
        that.width = img.width;
        that.height = img.height;
      };
    },
    //查看视频
    reviewVideo(obj) {
      this.src = obj.showUrl;
      this.dialogVisiblee = true;
    },

    proFileExceed() {
      this.$message.error("只允许上传一个文件");
    },
    //根据订单ID查询附件
    getOrderFileByNumber(id) {
      productDetails({ orderNumber: id }).then((res) => {
        this.accList = res.data;
        for (let key in res.data) {
          this.$nextTick(() => {
            new window.Viewer(document.getElementById("jq" + key));
          });
        }
      });
    },

    //第一次获取订单号
    getOrderNumber(type, faceType) {
      faceType = faceType.substring(faceType.length - 4, faceType.length);
      if (faceType == "face" || faceType == "back") {
        this.faceBack = faceType;
      } else {
        this.faceBack = "";
      }
      this.type = type;
      //如果type==8 就可以上传视频格式 20220406
      if (this.type == 8) {
        this.fileType =
          ".wmv,.asf,.asx,.rm,.rmvn,.mpg,.mpeg,.mpe,.3gp,.mov,.mp4,.m4v,.avi,.dat,.mkv,.flv,.vob";
      } else {
        this.fileType =
          ".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF";
      }

      if (!this.orderNumber) {
        getOrderNumber({ productId: this.productId }).then((res) => {
          this.orderNumber = res.data;
        });
      }
      this.$refs.files[0].click();

    },
    //获取oss
    async getOssOrder() {
      return new Promise((resolve, reject) => {
        getOssOrder().then(res => {
          this.ossInfo = res.data;
          resolve(res.data);
        }).catch((err) => {
          reject(err);
        });
      });

    },
    //上传oss
    async uploadOss(ossUrl, formData, config) {
      let that = this;
      return new Promise((resolve, reject) => {
        that.axios
          .post(ossUrl, formData, config)
          .then((res) => {
            if (res.status == 200) {
              resolve(true);
            }
          })
          .catch(() => {
            this[`loading${this.type}`] = false;
            this[`height${this.type}`] = 0;
            reject(false);

          });
      });


    },

    async uploadData(e) {
      let files = e.target.files;
      this.uploadImg(files);
    },
    //上传图片
    async uploadImg(params) {
      let that = this;
      let type = this.type;
      this[`loading${type}`] = true;
      this[`height${type}`] = 150;
      //表头信息
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };

      for (let i = 0; i < params.length; i++) {
        let dataOss = await this.getOssOrder();
        let imgName = params[i].name;
        let wz = imgName.split(".");
        let imgType = "." + wz[wz.length - 1];
        //创建文件
        let formData = new FormData();
        let ossUrl = dataOss.host;
        let index = params[i].type.indexOf("/");
        let typeSuffix = params[i].type.substring(0, index);
        //传文件成功后需要的参数
        that.fileForm = {
          accessoryShowName: imgName,
          accessorySaveName: dataOss.fileName,
          accessorySize: params[i].size,
          accessoryType: this.type,
          orderNumber: this.orderNumber,
          faceBack: this.faceBack
        };
        if (typeSuffix == "image") {
          //图片上传
          formData.append("policy", dataOss.policy);
          formData.append("key", dataOss.dir + dataOss.fileName + imgType);
          formData.append("OSSAccessKeyId", dataOss.accessid);
          formData.append("Signature", dataOss.signature);
          formData.append("success_action_status", 200);
          formData.append("fileName", dataOss.fileName);
          formData.append("file", params[i]);
          await this.uploadOss(ossUrl, formData, config);
          await this.addImg(this.fileForm, type);

        } else {
          //视频上传
          this.uploader.addFile(params[i]);
          let new_multipart_params = {
            "policy": dataOss.policy,
            "key": dataOss.dir + dataOss.fileName + imgType,
            "OSSAccessKeyId": dataOss.accessid,
            "Signature": dataOss.signature,
            "success_action_status": "200", //让服务端返回200,不然，默认会返回204
            "fileName": dataOss.fileName
          };

          this.uploader.setOption({
            url: dataOss.host,
            multipart_params: new_multipart_params
          });
          this.uploader.start();
        }

      }

    },
    //添加图片
    async addImg(params, type) {
      let that = this;
      return addOrderImg(params)
        .then((res) => {
          let resData = res.data;
          resData.showUrl = res.data.accessoryUrl;
          resData.showUrlMin = res.data.accessoryShrinkName;
          productDetails({ orderNumber: this.orderNumber }).then((res) => {
            this.accList = res.data;
          });
          that[`loading${type}`] = false;
          that[`height${type}`] = 0;
        })
        .catch(() => {
          that[`loading${this.type}`] = false;
          that[`height${this.type}`] = 0;
        });
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //删除图片
    deleteData(id) {
      delOssPic(id).then((res) => {
        this.$message({
          message: res.message,
          type: "success"
        });
        productDetails({ orderNumber: this.orderNumber }).then((res) => {
          this.accList = res.data;
        });
      });
    }


  }
};
</script>

<style scoped>
::v-deep .el-upload-list {
  display: none;
  width: 100%;
}

.title_div {
  line-height: 56px;
  position: relative;
  height: 56px;
  text-align: left;
  border-bottom: 1px solid #ededed;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.title_div span {
  font-family: Microsoft YaHei;
  font-size: 15px;
  font-weight: 400;
  height: 15px;
  color: rgba(51, 51, 51, 1);
}

.upload-demo {
  display: inline-block;
  float: right;
}

.addpic {
  color: #fff !important;
  border: 1px solid #ffa32f !important;
  background: #ffa32f !important;
}

.addpic:hover {
  color: #fff;
  border: 1px solid #ffa32f;
  background: #ffa32f;
}

.uploadDiv {
  overflow: hidden;
  margin-top: 10px;
}

.upload_list {
  overflow: hidden;
}

.upload_list ul {
  margin-right: -12px;
}

.upload_list li {
  position: relative;
  float: left;
  box-sizing: border-box;
  width: 49%;
  height: 130px;
  margin-top: 20px;
  margin-right: 20px;
  padding: 20px;
  text-align: left;
  border: 1px solid rgba(237, 237, 237, 1);
  border-radius: 8px;
}

.upload_list li:nth-child(even) {
  margin-right: unset;
}

.upload_list .img {
  float: left;
  overflow: hidden;
  width: 160px;
  height: 90px;
  margin-right: 20px;
  border-radius: 6px;
}

.upload_list .btn {
  position: absolute;
  top: 20px;
  right: 20px;
}

.upload_list .name {
  font-family: Microsoft YaHei;
  font-size: 14px;
  font-weight: 400;
  overflow: hidden;
  max-width: 66%;
  max-height: 20px;
  margin-top: 5px;
  margin-bottom: 14px;
  color: rgba(51, 51, 51, 1);
}

.upload_list .ztc {
  color: #999;
}

.downloadImagee {
  position: absolute;
  top: 13px;
  right: 60px;
  color: #fff !important;
  border: 1px solid #ffa32f !important;
  background: #ffa32f !important;
}

.previewImg {
  width: 100%;
  height: 100%;
}

.viewButton {
  font-size: 14px;
  position: absolute;
  top: 10px;
  right: 40px;
  display: inline-block;
  width: 50px;
  height: 26px;
  cursor: pointer;
  color: #409eff;
  border: 1px solid transparent;
  background-color: transparent;
}

.deleteStyle {
  font-size: 14px;
  position: absolute;
  top: 12px;
  right: 0;
  display: inline-block;
  width: 50px;
  height: 26px;
  cursor: pointer;
  color: #409eff;
  border: 1px solid transparent;
  background-color: transparent;
}

.titleStyle {
  position: absolute;
  top: 12px;
  left: 200px;
}
</style>
